/*
 * @Author: Mario
 * @Date:   2017-07-04 16:29:30
 * @Last Modified by:   Mario
 * @Last Modified time: 2017-07-04 19:40:48
 */
//img preload
'use strict';
(function($) {
    function PreLoad(imgs, options) {
        this.imgs = (typeof imgs === 'string') ? [imgs] : imgs;
        this.opts = $.extend({}, PreLoad.DEFAULTS, options);

        if (this.opts.order === 'ordered') {
            this._ordered();
        } else {
            this._unordered();
        }

    }
    PreLoad.DEFAULTS = {
        order: 'unordered', //无序预加载
        each: null, //每一张图片加载完毕后执行
        all: null //所有图片加载完毕后执行

    };
    //无序加载
    PreLoad.prototype._unordered = function() {
        var imgs = this.imgs,
            opts = this.opts,
            count = 0,
            len = imgs.length;
        $.each(imgs, function(i, src) {
            if (typeof src != 'string') return;
            var imgObj = new Image();
            $(imgObj).on('load error', function() {
                opts.each && opts.each(count);
                count++;
                if (count > len - 1) {
                    opts.all && opts.all();
                }

            });
            imgObj.src = src;
        });
    };

    //有序预加载
    PreLoad.prototype._ordered = function() {
        var imgs = this.imgs,
            opts = this.opts,
            count = 0,
            len = imgs.length;

        load();
        //有序yujiaz
        function load() {
            //第一步 先创建img对象
            var imgObj = new Image();
            //第二步 绑定load error事件 
            $(imgObj).on('load error', function() {
            	opts.each&&opts.each(count);
                
                count++;
                if (count >= len) {
                    //所有图片加载完毕
                    opts.all&&opts.all();
                } else {
                    load(); //自身调用
                }
            });
            //将当前图片的路径赋值给img对象的src来开始预加载
            imgObj.src = imgs[count];
        }
    };




    //$.fn.extend -> $('#img').preload();
    //$.extend -> $.preload();
    $.extend({
        preload: function(imgs, opts) {
            new PreLoad(imgs, opts);
        }
    })
})(jQuery)
